import React from 'react'
import {Modal, Form, Input, Select, message} from 'antd';
import api from "../../../../api/api";
import axios from "axios/index";
import PropTypes from 'prop-types'
//import {message} from "antd/lib/index";
const {Option} = Select;
const FormItem = Form.Item;

@Form.create()
class Model extends React.Component {
    //formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            intervalObj: Object,
            param: {
                meterialId: "",
                type: "",
                meterialName: "",
                companyId: "",
                companyName: "",
                createTime: "",
                orgCode: ""
            }
        };
    }

    componentDidMount() {
        console.log("dialog初始化==", this.props);
        this.clearData()
        this.props.onRef(this)
        this.getCompanySelect();
    }

    componentWillUnmount() {
        clearInterval(this.state.intervalObj)
    }

    handleOk = () => {
        console.info("2222222222222222222");
        this.props.form.validateFields((error, values) => {
            if (error != null) {
                return;
            }
            let {param} = this.state
            console.info("param", this.state)
            // param.meterialId = values.meterialId
            param.type = values.type
            param.meterialName = values.meterialName
            param.companyId = values.companyId
            param.companyName = values.companyName
            this.setState({param}, () => {
                this.meterialtypeData()
            })
        })
    }

    setBaseInfo = () => {
        let data = this.props.data.gridList
        console.info("data", data)
        const {form} = this.props;

        const {param} = this.state;
        clearInterval(this.state.intervalObj)
        param.companyId = data.companyId;
        Object.keys(form.getFieldsValue()).forEach(key => {
            const obj = {};
            if (data[key]) {
                obj[key] = data[key] || null;
            }
            form.setFieldsValue(obj);
        });
    };

    //清空form表单数据
    clearData() {
        this.props.form.resetFields();
    }

    //初始化编辑数据
    initEditData = () => {
        let that = this;
        this.getCompanySelect();
        this.state.intervalObj = setInterval(function () {
            that.setBaseInfo()
        }, 200)
    }


    meterialtypeData() {
        let url = ""
        if (this.props.data.type === 2) {
            url = api.api_URL + "/admin/meterialtype/updateMeterialType"
            let {param} = this.state
            console.info("param", this.state.param)
            console.info("meterialId====", this.props.data.gridList.meterialId)
            //param.companyId = this.props.data.gridList.companyId
            //param.meterialName = this.props.data.gridList.meterialName
            //param.companyName = this.props.data.gridList.companyName
            param.meterialId = this.props.data.gridList.meterialId
            this.setState({param}, () => {
                this.addMeterialType(url)
            })
        } else {
            url = api.api_URL + "/admin/meterialtype/addMeterialType?orgCode=" + localStorage.getItem('orgCode');
            this.addMeterialType(url)
        }
    }


//添加
    addMeterialType(url) {
        const that = this;
        axios({
            method: 'POST',
            url: url,
            data: JSON.stringify(that.state.param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            message.success({content: "成功！"})
            that.handleCancel()
        })
            .catch(function (error) {
                console.log(error);
                message.error({content: "失败,请重新尝试！"})
            })
    }

    handleCancel = e => {
        console.log(e);
        this.props.handleCancel()
    };
//获取公司下拉框值
    factorySelect = [];

    getCompanySelect() {
        this.factorySelect = [];
        let that = this;
        let dataList = [];
        let url;
        url = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有公司数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.factoryId;
                data.label = facData.name;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key} value={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })
    }

//选择公司
    companyChange = (value) => {
        console.info("value=====================", value);
        const {param} = this.state;
        param.companyId = value;
        // this.setState({
        //     companyId: value
        // })
    }

    typeChange = (value) => {
        console.info("value=", value);
        this.setState({
            type: value
        })
    }

    render() {
        const {getFieldDecorator, getFieldError} = this.props.form
        return (
            <div>
                <Modal
                    title={this.props.data.title}
                    visible={this.props.data.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <Form ref={this.formRef} autoComplete="off" name="control-ref"
                          labelCol={{span: 4}}
                          wrapperCol={{span: 14}}
                          layout="horizontal"
                    >
                        <FormItem label="物资类型" name="type">
                            {getFieldDecorator("type", {})(
                                <Select placeholder="请选择类型" onChange={this.typeChange} allowClear>
                                    <Option key="A1">A1</Option>
                                    <Option key="A2">A2</Option>
                                    <Option key="A3">A3</Option>
                                    <Option key="B1">B1</Option>
                                    <Option key="B2">B2</Option>
                                    <Option key="B3">B3</Option>
                                    <Option key="B4">B4</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem label="物资名称" name="meterialName">
                            {getFieldDecorator("meterialName", {})(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="所属公司" name="companyId">
                            {getFieldDecorator("companyId", {})(
                                <Select  placeholder="请选择公司"
                                    onChange={this.companyChange} allowClear>
                                    {this.factorySelect}
                                </Select>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Model